/**
 * 内容的工具类
 * @author Yang
 * @date 2018-05-08
 * @version 1.0.1
 */
var Content= function () {

    var errors={
        "imageerror":{
            success:false,
            code:3,
            message:"请上传封面图"
        },
        "menuserror":{
            success:false,
            code:4,
            message:"请选择导航"
        },
        "tabs":{
            success:false,
            code: 5,
            message:"请选择选项"
        }
    }

    /**
     * 导航选择器
     * 用于选择导航
     *
     */
    var selectHandler= function(){
        $("#menusId").on("change",function () {
            var id= $(this).val();
            if (id==null || id===""){
                if (!$('.children').hasClass("hidden")) {
                    $('.children').addClass("hidden");
                }
                return;
            }
            $.ajax({
                type:"get",
                url:base+"/manage/menus/findByParent",
                data:{parentId:id},
                dataType:"json",
                success:function (data) {
                    if (data.success){
                        var arr= data.data;
                        if(arr.length>0){
                            $('.children').removeClass("hidden");
                            var html="";
                            for (var i=0; i<arr.length;i++){
                                html+="<option value='"+arr[i].id+"'>";
                                html+=arr[i].title+"</option>";
                            }
                            $("#childrenMenusId").html(html);
                            return;
                        }
                        $('.children').addClass("hidden");
                        return;
                    }
                    $('.children').addClass("hidden");
                }
            })
        });
        $("#menusId").on("change",function () {
            var id= $(this).val();
            console.log(id);
            if (id==null){
                return;
            }
            $.ajax({
                type:"get",
                url:"../menus/findTabs",
                data:{menusId:id},
                dataType:"json",
                success:function (data) {
                    if (data.success){
                        var len= data.data.length;
                        if (len>0){
                            $("#tabs").closest(".form-group").removeClass("hidden");
                            $("#tabs").closest('.form-group').prev('.hr-line-dashed').removeClass("hidden");
                            var datas= data.data;
                            var html="";
                            for (var i=0; i<datas.length; i++){
                                html+="<option value='"+datas[i]+"'> ";
                                html+=datas[i]+"</option>";
                            }
                            $('#tabs').append(html);
                        }
                    } 
                }
            })
        })
    };

    var uploadHandler= function () {
        var file= $("#file");
        file.on("change",function () {
            var file= this.files[0];
            var xml= new XMLHttpRequest();
            xml.open("post",base+"/admin/common/upload");
            var fd=new FormData();
            fd.append("type",5);
            fd.append("file",file);
            fd.append("isShear",false);
            xml.send(fd);
            xml.addEventListener("load",function (e) {
                var result= e.target.responseText;
                result=JSON.parse(result);
                console.log(result);
                if(result.success){
                    console.log("this is ok");
                    var html='<div class="file-box"><div class="file"><div class="icon">';
                    html+='<img src="'+result.data+'"  width="100%"/></div><div class="file-name">';
                    html+='<a href="javascript:;" class="btn btn-danger btn-xs"><i class="fa fa-times-circle"></i>';
                    html+='删除</a><input type="hidden" class="fileimage" value="'+result.data+'"></div>';
                    html+='</div></div>';
                    $("#file").parent().before(html);
                }
            })
        })
    };

    /**
     * 删除图片的函数
     *
     */
    var deleteImageHandler= function () {
      $('.form-group').on("click","a.btn-danger",function () {
          if (!$(this).children("i").hasClass("fa-times-circle")){
              return;
          }
          $(this).closest('.file-box').remove();
      })
    };

    var deleteHandler= function () {

    }

    var validateHandler= function () {
        $('form').validate({
            rules:{
                title:{
                    required:true,
                    remote:{
                        url:"validateTitle",
                        type:"get",
                    }
                },
                summary:"required",
                menusId:"required"
            },
            messages:{
                title:{
                    required:"必填",
                    remote:"标题已经存在"
                },
                summary:{
                    required:"必填"
                },
                menusId:{
                    required:"请选择导航"
                }
            },
            submitHandler:function (form) {
                var images=[];
                $(".fileimage").each(function () {
                   images.push($(this).val());
                });
                var params={};
                var menusId=$("#menusId").val();
                var tabs= $("#tabs").val();
                if (tabs=="" || tabs==null){
                    Common.alert(errors.tabs);
                    return;
                }
                params.title= $("#title").val();
                params.explain= $("#summary").val();
                params.content= $("#editor").val();
                params.menusId=menusId;
                params.coveres= images;
                params.tabs= tabs;
                params= JSON.stringify(params);
                $.ajax({
                    type:"post",
                    url:"submit",
                    data:{params:params},
                    headers:{"token":token},
                    dataType:"json",
                    success:function (data) {
                        Common.alert(data);
                        if (data.success){
                            setTimeout(function () {
                                location.href="index.html";
                            },1500)
                            return;
                        }
                        location.reload(true)
                    }
                })
            }
        })
    };

    var updateHandler=function () {
        $('form').validate({
            rules:{
                title:{
                    required:true,
                    remote:{
                        type:"get",
                        url:"validateTitle",
                        data:{
                            title:function () {
                                return $("#title").val();
                            },
                            id:function () {
                                return $("#id").val();
                            }
                        },
                        dataFilter:function (data,args) {
                            return data;
                        }
                    }
                },
                explain:"required"
            },
            messages:{
                title:{
                    required:"必填",
                    remote:"标题已经存在"
                },
                explain:{
                    required:"必填"
                }
            },
            submitHandler:function (form) {
                var images=[];
                $(".fileimage").each(function () {
                    images.push($(this).val());
                });
                var params={};
                params.title=$("#title").val();
                params.id= $("#id").val();
                params.explain= $("#explain").val();
                params.coveres= images;
                params.content= $("#editor").val();
                params= JSON.stringify(params);
                $.ajax({
                    type:"post",
                    url:"update",
                    data:{"params":params},
                    dataType:"json",
                    headers:{"token":token},
                    success:function (data) {
                        Common.alert(data);
                        if (data.success){
                            setTimeout(function () {
                                location.href="index.html";
                            },1500)
                            return;
                        }
                        location.reload(true)
                    }
                })
            }
        })
    }

    return{
        init:function () {
            //初始化导航选择
            selectHandler();

            //上传图片
            uploadHandler();

            //删除图片的函数
            deleteImageHandler();

            //提交数据
            validateHandler();
        },
        index:function () {
            //删除的函数
            deleteHandler();
        },
        update:function () {
            selectHandler();
            uploadHandler();
            deleteImageHandler();
            updateHandler();
        }
    }
}();